// components/search-bar/search-bar.js
Component({
  properties: {
    // 搜索关键词
    keyword: {
      type: String,
      value: "",
    },
    // 占位符文本
    placeholder: {
      type: String,
      value: "搜索宠物、话题...",
    },
    // 是否显示搜索面板
    showPanel: {
      type: Boolean,
      value: false,
    },
    // 搜索历史
    searchHistory: {
      type: Array,
      value: [],
    },
    // 热门话题
    hotTopics: {
      type: Array,
      value: [],
    },
  },

  data: {
    // 内部搜索关键词
    searchKeyword: "",
    // 是否显示清除按钮
    showClearBtn: false,
  },

  lifetimes: {
    attached() {
      this.setData({
        searchKeyword: this.properties.keyword,
      });
    },
  },

  observers: {
    keyword: function (keyword) {
      this.setData({
        searchKeyword: keyword,
        showClearBtn: !!keyword,
      });
    },
  },

  methods: {
    // 搜索输入
    onSearchInput(e) {
      const keyword = e.detail.value;
      this.setData({
        searchKeyword: keyword,
        showClearBtn: !!keyword,
      });

      // 触发输入事件
      this.triggerEvent("input", { keyword });
    },

    // 搜索确认
    onSearchConfirm(e) {
      const keyword = e.detail.value;
      if (keyword.trim()) {
        this.triggerEvent("confirm", { keyword });
      }
    },

    // 清除搜索
    onClearSearch() {
      this.setData({
        searchKeyword: "",
        showClearBtn: false,
      });

      // 触发清除事件
      this.triggerEvent("clear");
    },

    // 切换搜索面板
    onTogglePanel() {
      this.triggerEvent("toggle");
    },

    // 选择搜索历史
    onSelectHistory(e) {
      const keyword = e.currentTarget.dataset.keyword;
      this.setData({
        searchKeyword: keyword,
        showClearBtn: true,
      });
      this.triggerEvent("selectHistory", { keyword });
    },

    // 选择热门话题
    onSelectHotTopic(e) {
      const topic = e.currentTarget.dataset.topic;
      this.setData({
        searchKeyword: topic,
        showClearBtn: true,
      });
      this.triggerEvent("selectHotTopic", { topic });
    },

    // 清空搜索历史
    onClearHistory() {
      this.triggerEvent("clearHistory");
    },

    // 发布按钮点击
    onPublishTap() {
      this.triggerEvent("publish");
    },
  },
});
